/*
*  Copyright 2019-2023 oyun
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/package com.oyun.modules.medicine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oyun.modules.medicine.domain.DoctorPicture;
import com.oyun.modules.medicine.domain.Hospital;
import com.oyun.modules.medicine.domain.MedicinePicture;
import com.oyun.modules.medicine.domain.SingleMedicine;
import com.oyun.modules.medicine.domain.vo.SingleMedicineQueryCriteria;
import com.oyun.modules.medicine.mapper.MedicinePictureMapper;
import com.oyun.modules.medicine.mapper.SingleMedicineMapper;
import com.oyun.modules.medicine.service.SingleMedicineService;
import com.oyun.segment.convert.itmd.IntermediateCodeUtils;
import com.oyun.utils.FileUtil;
import com.oyun.utils.PageResult;
import com.oyun.utils.PageUtil;
import com.oyun.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
* @description 服务实现
* @author huhe
* @date 2024-06-28
**/
@Service
@RequiredArgsConstructor
public class SingleMedicineServiceImpl extends ServiceImpl<SingleMedicineMapper, SingleMedicine> implements SingleMedicineService {

    private final SingleMedicineMapper singleMedicineMapper;

    private final MedicinePictureMapper medicinePictureMapper;
    @Value("${file.windows.path}")
    private String path;


    @Override
    public PageResult<SingleMedicine> queryAll(SingleMedicineQueryCriteria criteria, Page<Object> page){
        if (StringUtils.isNotEmpty(criteria.getName())){
            criteria.setReplaceAll((IntermediateCodeUtils.mn2Code(criteria.getName()).replaceAll("-", " -")));
        }
        return PageUtil.toPage(singleMedicineMapper.findAll(criteria, page));
    }

    @Override
    public List<SingleMedicine> queryAll(SingleMedicineQueryCriteria criteria){
        return singleMedicineMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(SingleMedicine resources) {
        convertCode(resources);
        save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SingleMedicine resources) {
        SingleMedicine singleMedicine = getById(resources.getId());
        singleMedicine.copy(resources);
        convertCode(singleMedicine);
        saveOrUpdate(singleMedicine);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Long> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<SingleMedicine> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SingleMedicine singleMedicine : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("药品分类（字典）", singleMedicine.getType());
            map.put("蒙药名", singleMedicine.getMnName());
            map.put(" mnNameCode",  singleMedicine.getMnNameCode());
            map.put(" zhName",  singleMedicine.getZhName());
            map.put(" elName",  singleMedicine.getElName());
            map.put("蒙语别名", singleMedicine.getMnAnotherName());
            map.put(" mnAnotherNameCode",  singleMedicine.getMnAnotherNameCode());
            map.put(" zhAnotherName",  singleMedicine.getZhAnotherName());
            map.put(" elAnotherName",  singleMedicine.getElAnotherName());
            map.put("蒙语学名", singleMedicine.getMnScientificName());
            map.put(" mnScientificNameCode",  singleMedicine.getMnScientificNameCode());
            map.put(" zhScientificName",  singleMedicine.getZhScientificName());
            map.put(" elScientificName",  singleMedicine.getElScientificName());
            map.put("蒙语文献来源", singleMedicine.getMnDocument());
            map.put(" mnDocumentCode",  singleMedicine.getMnDocumentCode());
            map.put(" zhDocument",  singleMedicine.getZhDocument());
            map.put("蒙语生境", singleMedicine.getMnHabitat());
            map.put(" zhHabitat",  singleMedicine.getZhHabitat());
            map.put("蒙语入药部分", singleMedicine.getMnMedicatedPart());
            map.put(" zhMedicatedPart",  singleMedicine.getZhMedicatedPart());
            map.put("蒙语性味", singleMedicine.getMnNatureTaste());
            map.put(" mnNatureTasteCode",  singleMedicine.getMnNatureTasteCode());
            map.put(" zhNatureTaste",  singleMedicine.getZhNatureTaste());
            map.put("蒙语功能", singleMedicine.getMnFeature());
            map.put(" mnFeatureCode",  singleMedicine.getMnFeatureCode());
            map.put(" zhFeature",  singleMedicine.getZhFeature());
            map.put("蒙语主治", singleMedicine.getMnFunctionsDisease());
            map.put(" mnFunctionsDiseaseCode",  singleMedicine.getMnFunctionsDiseaseCode());
            map.put(" zhFunctionsDisease",  singleMedicine.getZhFunctionsDisease());
            map.put("蒙语副作用", singleMedicine.getMnSideEffect());
            map.put(" mnSideEffectCode",  singleMedicine.getMnSideEffectCode());
            map.put(" zhSideEffect",  singleMedicine.getZhSideEffect());
            map.put("蒙语临床使用", singleMedicine.getMnClinicalUse());
            map.put(" zhClinicalUse",  singleMedicine.getZhClinicalUse());
            map.put("蒙语解释", singleMedicine.getMnExplain());
            map.put(" zhExplain",  singleMedicine.getZhExplain());
            map.put("蒙语加工", singleMedicine.getMnProcess());
            map.put(" mnProcessCode",  singleMedicine.getMnProcessCode());
            map.put(" zhProcess",  singleMedicine.getZhProcess());
            map.put("蒙语存储", singleMedicine.getMnStore());
            map.put(" mnStoreCode",  singleMedicine.getMnStoreCode());
            map.put(" zhStore",  singleMedicine.getZhStore());
            map.put("蒙语参考资料", singleMedicine.getMnReferenceMaterial());
            map.put(" zhReferenceMaterial",  singleMedicine.getZhReferenceMaterial());
            map.put(" createBy",  singleMedicine.getCreateBy());
            map.put(" createTime",  singleMedicine.getCreateTime());
            map.put(" updateBy",  singleMedicine.getUpdateBy());
            map.put(" updateTime",  singleMedicine.getUpdateTime());
            map.put(" status",  singleMedicine.getStatus());
            map.put(" remark",  singleMedicine.getRemark());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public MedicinePicture uploadOrUpdate(MultipartFile file, HttpServletRequest request, Long id) {
        File filee = new File(path + "/single");
        if (!filee.exists()) {//不存在
            filee.mkdirs();
        }
        String filename = file.getOriginalFilename();//获取文件名称带后缀名
        String uid = UUID.randomUUID().toString();//生成32为uuid值
        String suffix = filename.substring(filename.lastIndexOf(".")); //切割获取.后面的jpg
        String newFile = uid + suffix;//拼接新的文件名称
        File file1 = new File(filee + "/" + newFile);
        try {
            file.transferTo(file1);
        } catch (IOException e) {
            e.printStackTrace();
        }

        MedicinePicture medicinePicture = new MedicinePicture();
        medicinePicture.setMedicineId(id);
        medicinePicture.setPathImage("/single/"+newFile);
        medicinePicture.setStatus(1);
        medicinePictureMapper.insert(medicinePicture);

//        LambdaQueryWrapper<DoctorPicture> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(id != null, DoctorPicture::getDoctorId, id).eq(DoctorPicture::getStatus, 1);
//        DoctorPicture picture = doctorPictureMapper.selectOne(wrapper);
//        if (picture == null) {
//            //新增
//            DoctorPicture doctorPicture = new DoctorPicture();
//            doctorPicture.setDoctorId(id);
//            doctorPicture.setPathImage("/doctor/" + newFile);
//            doctorPicture.setStatus(1);
//            doctorPictureMapper.insert(doctorPicture);
//        } else {
//            //修改
//            picture.setPathImage("/doctor/" + newFile);
//            picture.setStatus(1);
//            doctorPictureMapper.updateById(picture);
//        }
        return medicinePicture;
    }

    private void convertCode(SingleMedicine resources) {
        resources.setMnNameCode(IntermediateCodeUtils.mn2Code(resources.getMnName()).replaceAll("-", " -"));
//        resources.setMnAnotherNameCode(IntermediateCodeUtils.mn2Code(resources.getMnAnotherName()).replaceAll("-", " -"));
//        resources.setMnScientificNameCode(IntermediateCodeUtils.mn2Code(resources.getMnScientificName()).replaceAll("-", " -"));
//        resources.setMnDocumentCode(IntermediateCodeUtils.mn2Code(resources.getMnDocument()).replaceAll("-", " -"));
//        resources.setMnNatureTasteCode(IntermediateCodeUtils.mn2Code(resources.getMnNatureTaste()).replaceAll("-", " -"));
//        resources.setMnFeatureCode(IntermediateCodeUtils.mn2Code(resources.getMnFeature()).replaceAll("-", " -"));
//        resources.setMnFunctionsDiseaseCode(IntermediateCodeUtils.mn2Code(resources.getMnFunctionsDisease()).replaceAll("-", " -"));
//        resources.setMnSideEffectCode(IntermediateCodeUtils.mn2Code(resources.getMnSideEffect()).replaceAll("-", " -"));
//        resources.setMnProcessCode(IntermediateCodeUtils.mn2Code(resources.getMnProcess()).replaceAll("-", " -"));
//        resources.setMnStoreCode(IntermediateCodeUtils.mn2Code(resources.getMnStore()).replaceAll("-", " -"));
    }
}
